package com.xiangb.springbootjpa.controller;

import com.xiangb.springbootjpa.utils.JudgeCharsetUtils;
import org.apache.commons.io.IOUtils;
import org.jodconverter.DocumentConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * Description: <br>
 *
 * @author: XB
 * @date: 2021/7/7 14:55
 */
@Controller
public class FileToPdfController {

    @Autowired
    private DocumentConverter converter;

    @Autowired
    private HttpServletResponse response;

    /**
     * 文件转成pdf并在线预览
     * @param path 文件相对或绝对路径，如果是相对路径则在jvm所在的根目录下
     * @return
     */
    @RequestMapping("toPdfFile")
    @ResponseBody
    public String toPdfFile(String path) {
        System.out.println("文件" + path + "开始转换成pdf！");
        long old = System.currentTimeMillis();
        File file = new File(path);//需要转换的文件
        try {
            File newFile = new File("/file");//转换之后文件生成的地址
            if (!newFile.exists()) {
                newFile.mkdirs();
            }
            //文件转化
            converter.convert(file).to(new File(path.split("\\.")[0] + ".pdf")).execute();
            long now = System.currentTimeMillis();
            System.out.println("文件" + path + "开始转换成pdf成功！");
            System.out.println("共耗时：" + ((now - old) / 1000.0) + "秒");
            //使用response,将pdf文件以流的方式发送的前段
            ServletOutputStream outputStream = response.getOutputStream();
            InputStream in = new FileInputStream(new File(path.split("\\.")[0] + ".pdf"));// 读取文件
            // copy文件
            int i = IOUtils.copy(in, outputStream);
            System.out.println(i);
            in.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "This is to pdf";
    }


}
